
import type { MockMethod } from 'vite-plugin-mock'
import type { IncomingMessage, ServerResponse } from 'http'

function checkToken<T>({ req, res }: { req: IncomingMessage, res: ServerResponse }, responseData: T) {
  const token = req.headers.authorization
  res.setHeader('Content-Type', 'application/json')
  if (token) {
    res.statusCode = 200
    res.end(JSON.stringify(responseData))
  } else {
    res.statusCode = 401
    res.end(JSON.stringify({
      code: 401,
      message: 'Unauthorized',
    }))
  }
}

export default [
  {
    url: '/api/login',
    method: 'post',
    response: () => {
      return {
        code: 200,
        data: {
          token: Math.random().toString(36).substring(2, 15),
        },
      }
    },
  },
  {
    url: '/api/getUserInfo',
    method: 'get',
    timeout: 1000,
    rawResponse(req, res) {
      const token = req.headers.authorization
      if (token) {
        checkToken({ req, res }, {
          code: 200,
          data: {
            name: 'admin',
            avatar: 'https://fastly.picsum.photos/id/435/400/300.jpg?hmac=ioNGvQreAbTSwPGvGL63psMAlYMf_UNZjSjTsH5J1K4',
            tel: '13800138000',
            email: 'admin@example.com',
          }
        })
      } else {
        checkToken({ req, res }, {
          code: 401,
          message: 'Unauthorized',
        })
      }
    },
  },
  {
    url: '/api/refreshToken',
    method: 'post',
    rawResponse(req, res) {
      const token = req.headers.authorization
      
      if (token) {
        checkToken({ req, res }, {
          code: 200,
          data: {
            isRefreshToken: true,
            token: Math.random().toString(36).substring(2, 15),
          },
        })
      } else {
        checkToken({ req, res }, {
          code: 401,
          message: 'Unauthorized',
        })
      }
    },
  },
] as MockMethod[]